package com.ygqh.baby.controller;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.handler.OffShopBiOrderHandler;
import com.ygqh.baby.model.YgOrderInfoModel;
import com.ygqh.baby.po.BiSupplierOrderDay;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgReturnOrder;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.task.YgBalanceTaskService;
import com.ygqh.baby.service.task.YgBiTaskService;
import com.ygqh.baby.service.wdtqyb.api.WdtQybApi;
import com.ygqh.baby.service.wechat.model.good.GoodImportOrderRequestParam;
import com.ygqh.baby.service.wechat.service.WeixinGoodService;
import com.ygqh.baby.template.AbstractSplitListTemplate;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.MailUtil;
import com.ygqh.baby.utils.PlatformUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sunshuo
 * @Date: 2019/5/24 09:20
 * @Version: 1.0
 */
@Controller
@RequestMapping("repairData")
public class RepairDataController {

	@Autowired
	private WxSmallAuthorityService wxSmallAuthorityService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private WeixinGoodService weixinGoodService;
	@Autowired
	private RepairBalanceDataService repairBalanceDataService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private MailUtil mailUtil;
	@Autowired
	private YgProductService ygProductService;
	@Autowired
	private WdtQybApi wdtQybApi;
	@Autowired
	private YgBalanceTaskService ygBalanceTaskService;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	@Autowired
	private YgUserBalanceService ygUserBalanceService;
	@Autowired
	private OffShopBiOrderHandler offShopBiOrderHandler;
	@Autowired
	private YgBiTaskService ygBiTaskService;
	@Autowired
	private BiSupplierOrderDayService biSupplierOrderDayService;

	/**
	 * 刷新指定token
	 *
	 * @param platformNo 平台
	 * @return
	 * @throws WeixinException
	 */
	@RequestMapping("refreshToken")
	@ResponseBody
	public Message refreshToken(String platformNo) throws WeixinException {
		TokenHolder tokenHolder = wxSmallAuthorityService.findTokenHolder(platformNo);
		tokenHolder.refreshToken();
		return Message.success(null);
	}

	/**
	 * 获取redis keys
	 *
	 * @param prefix 匹配（例如：abc*）
	 * @return
	 */
	@RequestMapping("getRedisKey")
	@ResponseBody
	public Message getRedisKey(String prefix) {
		Set<byte[]> keys = redisDao.keys(prefix);
		List<String> list = new ArrayList<>();
		for (byte[] key : keys) {
			list.add(new String(key));
		}
		return Message.success(list);
	}

	/**
	 * 删除redis value(慎用)
	 *
	 * @param prefix 匹配（例如：abc*）
	 * @return
	 */
	@RequestMapping("delRedisData")
	@ResponseBody
	public Message delRedisData(String prefix) {
		Set<byte[]> keys = redisDao.keys(prefix);
		List<String> list = new ArrayList<>();
		for (byte[] key : keys) {
			list.add(new String(key));
			redisDao.del(key);
		}
		return Message.success(list);
	}

	/**
	 * 导入订单到微信好物圈
	 * @param orderId
	 * @param isHistory
	 * @return
	 */
	@RequestMapping("importOrderToWeixinGood")
	@ResponseBody
	public Message importOrderToWeixinGood(Long orderId, @RequestParam(defaultValue = "0") Integer isHistory,
					@RequestParam(defaultValue = "ADD_ORDER") GoodImportOrderRequestParam.ImportOrderAction action) {
		weixinGoodService.importOrder(orderId, isHistory, action);
		return Message.success(null);
	}

	/**
	 * 修复预计收入
	 *
	 * @param orderIds
	 * @param returnCodes
	 * @return
	 */
	@RequestMapping("repairPreBalanceData")
	@ResponseBody
	public Message repairPreBalanceData(Long[] orderIds, String[] returnCodes) {
		repairBalanceDataService.repairPreBalanceData(orderIds, returnCodes);
		return Message.success(null);
	}

	/**
	 * 批量导入订单到微信好物圈
	 *
	 * @param startTime
	 * @param endTime
	 * @param isHistory
	 * @return
	 */
	@RequestMapping("importHistoryOrderToWeixin")
	@ResponseBody
	public Message importHistoryOrderToWeixin(Date startTime, Date endTime, String platformNo,
					  @RequestParam(defaultValue = "0") Integer isHistory,
					  @RequestParam(defaultValue = "ADD_ORDER") GoodImportOrderRequestParam.ImportOrderAction action) {
		List<YgOrderInfoModel> orderList = ygOrderService.findOrderInfoByPayTime(startTime, endTime, platformNo);
		int size = CollectionUtils.isEmpty(orderList) ? 0 : orderList.size();
		String content = "【批量导入订单到微信好物圈】参数：startTime=" + DateConvertUtils.formatDateTime(startTime) + ", " +
				"endTime=" + DateConvertUtils.formatDateTime(endTime) + ", " +
				"platformNo=" + platformNo +", " + "isHistory=" + isHistory +", " +
				"size=" + size;
		System.out.println(content);
		mailUtil.simpleSend("sunshuo@yiigoo.com", "批量导入订单到微信好物圈",
				content);
		int row = new AbstractSplitListTemplate<YgOrderInfoModel>(orderList, 10) {
			@Override
			public int execute(List<YgOrderInfoModel> recordList) {
				weixinGoodService.importOrderBatch(recordList, isHistory, action);
				return recordList.size();
			}
		}.split();
		return Message.success(row);
	}

	/**
	 * 导入物品到微信好物圈
	 *
	 * @param productId
	 * @return
	 */
	@RequestMapping("importProductToWeixin")
	@ResponseBody
	public Message importProductToWeixin(Long productId) {
		weixinGoodService.importProduct(productId);
		return Message.success(null);
	}

	/**
	 * 批量导入物品到微信好物圈
	 *
	 * @param startTime
	 * @param endTime
	 * @param platformNo
	 * @return
	 */
	@RequestMapping("importHistoryProductToWeixin")
	@ResponseBody
	public Message importHistoryProductToWeixin(Date startTime, Date endTime, String platformNo) {
		List<YgProduct> productList =
				ygProductService.findDetailBySaleTime(startTime, endTime, PlatformUtil.converte(platformNo));
		int size = CollectionUtils.isEmpty(productList) ? 0 : productList.size();
		String content = "【批量导入物品到微信好物圈】参数：startTime=" + DateConvertUtils.formatDateTime(startTime) + ", " +
				"endTime=" + DateConvertUtils.formatDateTime(endTime) + ", " +
				"platformNo=" + platformNo +", " +
				"size=" + size;
		System.out.println(content);
		mailUtil.simpleSend("sunshuo@yiigoo.com", "批量导入物品到微信好物圈",
				content);
		int row = new AbstractSplitListTemplate<YgProduct>(productList, 10) {
			@Override
			public int execute(List<YgProduct> recordList) {
				weixinGoodService.importProduct(recordList);
				return recordList.size();
			}
		}.split();
		return Message.success(row);
	}

	/**
	 * 批量导入订单到旺店通
	 *
	 * @param orderIds 订单编号集
	 * @return 导入失败订单
	 */
	@RequestMapping("batchPushOrderToWdt")
	@ResponseBody
	public Message batchPushOrderToWdt(Long[] orderIds) {
		return wdtQybApi.tradePushByOrderIds(Arrays.asList(orderIds));
	}

	/**
	 * 拼团订单退预收入
	 *
	 * @param orderId 订单编号
	 * @return
	 */
	@RequestMapping("doCancelGroupOrder")
	@ResponseBody
	public Message doCancelGroupOrder(Long orderId) {
		List<YgReturnOrder> returnList = ygReturnOrderService.findRetrunByOrderId(orderId);
		List<String> collect = null;
		if (CollectionUtils.isNotEmpty(returnList)) {
			collect = returnList.stream().filter(o ->
					ReturnType.Return.equals(o.getReturnType()) && ReturnStatus.Complete.equals(o.getReturnStatus())).
					map(YgReturnOrder::getReturnCode).
					collect(Collectors.toList());
		}
		ygBalanceTaskService.doCancelGroupOrder(orderId, collect);
		return Message.success(null);
	}

	@RequestMapping("resetUserBalance")
	@ResponseBody
	public Message resetUserBalance(BalanceType balanceType, Long[] userId) {
		ygUserBalanceService.resetUserBalance(balanceType, Arrays.asList(userId));
		return Message.success(null);
	}

	@RequestMapping("statisticsOffShopOrder")
	@ResponseBody
	public Message statisticsOffShopOrder(Date startTime, Date endTime, OffShop... offShops) {
		offShopBiOrderHandler.statisticsOrderByTime(startTime, endTime, offShops);
		return Message.success(null);
	}

	@RequestMapping("statisticsSupplierOrderByDate")
	@ResponseBody
	public Message statisticsSupplierOrderByDate(Date startDate, Date endDate, OffShop... offShops) {
		List<BiSupplierOrderDay> orderDayList =
				offShopBiOrderHandler.statisticsSupplierOrderByDate(startDate, endDate, offShops);
		if (CollectionUtils.isNotEmpty(orderDayList)) {
			biSupplierOrderDayService.saveBatch(orderDayList);
		}
		return Message.success(null);
	}

	@RequestMapping("statisticsSupplierOrderByHistory")
	@ResponseBody
	public Message statisticsSupplierOrderByHistory(Date startDate, Date endDate) {
		ygBiTaskService.statisticsSupplierOrderByHistory(startDate, endDate);
		return Message.success(null);
	}
}
